package Top4.mandatory;

import com.rabbitmq.client.*;
import util.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Auther: Administrator
 * @Date: 2019/2/27 14:14
 * @Description: 上面代码中生产者没有成功地将消息路由到队列，此时 RabbitMQ 会通过 Basic.Return
 * 返回 " mandatory test " 这条消息，之后生产者客户端通过 ReturnListener 监昕到了这个事
 * 件，上面代码的最后输出应该是" Basic.Retum 返回的结果是 : mandatory 忧test "
 *
 */
public class MandatoryProducer {
    private static final String EXCHANGE_NAME = "mandatory_exchange_demo";
    private static final String ROUTING_KEY = "mandatory_routingkey_demo";
    private static final String QUEUE_NAME = "mandatory_queue_demo";
    private static final String IP_ADDRESS = "192.168.204.130";
    private static final int PORT = 5672;//RabbitMQ 服务端默认端口号为 5672

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        String message = "Mandatory Test";
        //发送时候调用的是路由键
        // 创建一个 type="direct" 、持久化的、非自动删除的交换器
        channel.exchangeDeclare(EXCHANGE_NAME, "direct", true, false, null);
        //当 mandatory 参数设为 true 时，交换器无法根据自身的类型和路由键找到一个符合条件
        //的队列，那么 RabbitMQ 会调用 Basic.Return 命令将消息返回给生产者 。当 mandatory 参
        //数设置为 false 时，出现上述情形，则消息直接被丢弃 。
        channel.queueDeclare(QUEUE_NAME, true, false, false, null);
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "aaaaaaaa");
        channel.basicPublish(EXCHANGE_NAME, "1111", true, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());


        //当交换器没有绑定任何队列    设施mandatory属性 之后 路由键和绑定键皮配不上  之后回调
        channel.addReturnListener(new ReturnListener() {
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("=========handleReturn===method============");
                System.out.println("replyText:" + replyText);
                System.out.println("exchange:" + exchange);
                System.out.println("routingKey:" + routingKey);
                System.out.println("message:" + new String(body));
            }
        });

        //
        connection.close();
    }

}
